<template>
    <section class="app-inner">
      <el-dialog v-if="dialogVisible" :visible.sync="dialogVisible" :before-close="handleClose" :title="title" center width="800px">

        <el-form ref="editFormRef" :model="editForm" :rules="rules" size="small">
          <el-form-item label="学段/年级/入学年份" :label-width="148+'px'" prop="className" class="line">
            <el-input v-model="editForm.gradeAndYear" auto-complete="off" disabled class="inputWidth"></el-input>
          </el-form-item>

          <el-form-item label="班级名称" :label-width="labelWidth" prop="name" class="line">
            <!-- <el-input v-model="editForm.name" auto-complete="off"></el-input> -->
            <el-select @change="changeClassNum" class="inputWidth" v-model="editForm.name" clearable auto-complete="off">
              <el-option
                v-for="item in classNameList"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="班级人数" :label-width="labelWidth" prop="className" class="line">
            <el-input type="value" v-model="editForm.classSize" auto-complete="off" class="inputWidth"></el-input>
          </el-form-item>

          <el-form-item label="班主任" :label-width="labelWidth" prop="headerNo" class="line">
            <div class="teacherBtn">
              <!-- <el-select filterable v-model="editForm.headerNo" class="selectHead" placeholder="请选择班主任" auto-complete="off">
                <el-option
                  v-for="item in selectTeacherList"
                  :key="item.no"
                  :label="item.name"
                  :value="item.no"
                ></el-option>
              </el-select> -->
              <el-input class="selectHead1" disabled placeholder="请选择班主任" v-model="headerName"></el-input>
              <!-- <el-input v-else v-model="editForm.headName" class="selectHead" clearable></el-input> -->
              <div class="btns">
                <el-button type="primary" class="choose" @click="chooseTeacher">选择</el-button>
                <el-button type="primary" class="choose" @click="addTeacherFn">新增教师</el-button>
              </div>
              <!-- <el-button type="primary">刷新</el-button> -->
            </div>
          </el-form-item>

          <el-form-item label="教室" :label-width="labelWidth" prop="className" class="line">
            <div class="classRoom">
              <el-select v-model="editForm.classRoomNo" filterable
              placeholder="请选择教室" class="selectWidth" auto-complete="off">
                <el-option
                  v-for="item in classRoomList"
                  :key="item.no"
                  :label="item.name"
                  :value="item.no"
                ></el-option>
              </el-select>
              <!-- <el-input class="selectHead" clearable v-else v-model="classRoomN"></el-input> -->
              <el-button type="primary" @click="addClassRoomFn">新增教室</el-button>
              <!-- <el-button type="primary" @click="refreshClassRoom">刷新</el-button> -->
            </div>
          </el-form-item>

          <el-form-item label="班级状态" :label-width="labelWidth" prop="status" class="line">
            <!-- <template slot-scope="scope"> -->
              <el-radio v-model="editForm.status" label="1">有效</el-radio>
              <el-radio v-model="editForm.status" label="0">无效</el-radio>
            <!-- </template> -->
          </el-form-item>
        </el-form>

        <div class="itemWrapper">
          <span class="itemTitle">任课教师信息</span>
          <el-button type="primary" class="itemBtn" :disabled="teacherTableData.length === subjects.length" @click="addCourseFn">新增课程</el-button>
        </div>

        <el-table border :data="teacherTableData" style="width: 100%">
          <el-table-column type="index" label="序号" width="120"></el-table-column>

          <el-table-column prop="subjectNo" label="学科">
            <template slot-scope="scope">
              <el-select v-model="scope.row.subjectNo" @change="changeSubject(scope.row)"
              placeholder="请选择学科" clearable
              class="subjectSelect" auto-complete="off">
                <el-option
                  v-show="item.flag"
                  v-for="item in subjects"
                  :key="item.no"
                  :label="item.name"
                  :value="item.no"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>

          <el-table-column prop="teacherName" label="任课老师">
            <template slot-scope="scope">
              <!-- <el-select filterable v-model="scope.row.teacherNo" class="subjectSelect" placeholder="请选择任课教师" auto-complete="off">
                <el-option
                  v-for="item in selectTeacherList"
                  :key="item.no"
                  :label="item.name"
                  :value="item.no"
                ></el-option>
              </el-select> -->
              <el-input v-model="scope.row.teacherName" placeholder="请选择任课教师"
               disabled class="subjectSelect" auto-complete="off"></el-input>
              <el-button type="primary" class="btnCss" size="small" @click="editTeacherFn(scope.row, scope.$index)">选择</el-button>
            </template>
          </el-table-column>

          <!-- <el-table-column label="操作">
              <template slot-scope="scope">
              </template>
          </el-table-column> -->
        </el-table>

        <div slot="footer" class="dialog-footer">
            <el-button @click="handleCancel()" size="small">取 消</el-button>
            <el-button type="primary" @click="hanldeSave('editFormRef')" size="small">确 定</el-button>
        </div>

      </el-dialog>
      <!-- <course-teacher ref="courseTeacher"></course-teacher> -->
      <add-teacher ref="addTeacher" @addTeacherReq="addTeacherReq"></add-teacher>
      <addTeachInfo :infoData="infoData" :deptData="departments" :addTeachForm="addTeachForm" :data="addTeachFormData" @closeaddTeachForm="addTeachForm.flag = false"/>
      <classroomInfoModal ref="classroomInfoModal" @ok="modalOk"></classroomInfoModal>
    </section>
</template>

<script>
// import courseTeacher from './courseTeacher.vue'
import { Message } from 'element-ui'
import addTeachInfo from './addTeachInfo'
import classroomInfoModal from '../modules/classroomInfoModal.vue'
import { getClassRoomList } from '../js/classRoomInfo'
import { teacherList } from '../js/gradeInfo.js'
import addTeacher from './addTeacher.vue'
import { getSubjectAndId } from '../js/subjectInfo.js'
// import { queryPage } from '../js/teacherInfo.js'
import { editorClass, detailClass } from '../js/class.js'
import { queryDeptListBySchoolNo } from '@/views/children/basic/js/teacherInfo'
export default {
  name: 'editorClass',
  components: {
    // courseTeacher,
    addTeacher,
    addTeachInfo,
    classroomInfoModal
  },
  provide () {
    return {
      handleSearch: this.getTeacherList
    }
  },
  data () {
    return {
      dialogVisible: false,
      title: '基本信息',
      labelWidth: '148px',
      headerName: '',
      classRoomN: '',
      infoData: {}, // 字典数据
      departments: [], // 部门数据
      classNameList: [],
      // 新增
      addTeachForm: {
        flag: false,
        title: ''
      },
      addTeachFormData: {},
      classRoomList: [],
      editForm: {
        status: '',
        headerNo: '',
        classRoomNo: ''
      },
      period: '',
      selectTeacherList: [],
      subjects: [],
      currentRow: 0,
      teacherTableData: [],
      SepClassesUpdateReq: {
        classRoomNo: '',
        classSection: '',
        classSize: null,
        gradeNo: '',
        headerNo: '',
        isMinority: null,
        minorityCode: null,
        name: '',
        no: '',
        status: null,
        subjects: [],
        type: ''
      },
      currentTeacherRow: -1,
      debounceNum: 1000,
      rules: {
        name: [{ required: true, message: '请输入班级名称' }],
        status: [{ required: true, message: '请选择班级状态' }],
        headerNo: [{ required: true, message: '请选择班主任' }]
      }
    }
  },
  computed: {},
  methods: {
    async add (row) {
      this.dialogVisible = true
      // this.getTeacherList()
      this.getSubjectList()
      let temp = await this.getDetailClass(row.classNo) // 获取班级课程数据
      const tempObj = {
        classRoomNo: temp.classRoomNo || '',
        status: temp.status.toString()
      }
      this.queryDeptListBySchoolNo() // 获取部门数据
      this.editForm = {
        ...row,
        ...tempObj }
      this.headerName = row.headName
      // 基础数据获取
      this.editForm.classSection = row.period
      this.editForm.name = row.name
      this.initClassNameList() // 初始化班级名称列表
      this.SepClassesUpdateReq.no = row.classNo
      /*
        学段年级入学年份  拼接
      */
      if (row.period) {
        this.period = this.$dictionary.period.filter(item => {
          if (item.code === row.period) {
            return item
          }
        })
        this.$nextTick(() => {
          this.editForm.gradeAndYear = `${this.period[0].name}/${row.gradeName}/${row.year}`
        })
      } else {
        this.editForm.gradeAndYear = `${row.gradeName}/${row.year}`
      }
      this.selectClassRoomFn()
    },

    // 获取该班级学科数据
    async getDetailClass (data) {
      try {
        let res = await detailClass(data)
        if (res.code === 0) {
          this.teacherTableData = res.data.list
          // this.editForm.classRoomNo = res.data.classRoomNo
          this.SepClassesUpdateReq.classRoomNo = res.data.classRoomNo
          this.SepClassesUpdateReq.headerNo = res.data.headerNo
          this.SepClassesUpdateReq.gradeNo = res.data.gradeNo
          this.SepClassesUpdateReq.status = res.data.status
          // 课程表格数据整理
          return res.data
        }
      } catch (e) {}
    },

    // 初始化班级名称列表
    initClassNameList () {
      const name = this.editForm.name.includes('高') || this.editForm.name.includes('初') ? this.editForm.name.substring(0, 2) : this.editForm.name.substring(0, 1)
      let i = 1
      let tempArr = []
      for (i; i <= 30; i++) {
        let obj = {}
        obj.name = `${name}（${i}）班`
        obj.value = `${name}（${i}）班`
        tempArr.push(obj)
      }
      this.classNameList = tempArr
    },
    // 更改班级名称
    changeClassNum () {
    },

    // 关闭弹窗
    handleClose () {
      this.dialogVisible = false
      this.editForm = Object.assign({}, this.editForm)
    },

    // 班主任选择器
    async getTeacherList () {
      let query = {
        positionType: '1'
      }
      let res = await teacherList(query)
      this.selectTeacherList = res.data
    },

    // 教室选择器
    async selectClassRoomFn () {
      try {
        let res = await getClassRoomList()
        if (res.code === 0) {
          this.classRoomList = res.data
        }
      } catch (e) {}
    },
    // 改变选中的教室
    // handleChangeRoom (value) {
    //   this.editForm.classRoom = this.classRoomList.filter(item => item.id === value)[0].name
    //   this.SepClassesUpdateReq.classRoomNo = value
    // },

    // 学科选择器
    async getSubjectList () {
      let res = await getSubjectAndId()
      if (res.code === 0) {
        this.subjects = res.data
      }
      this.subjects.forEach(item => {
        item.flag = true
      })
    },

    // 已选择的下拉框数据不显示
    changeSubject (row) {
      this.subjects.forEach(tempItem => {
        tempItem.flag = true
      })
      this.filterItem()
    },

    // 筛选未选择的下拉框数据
    filterItem () {
      this.teacherTableData.forEach(item => {
        this.subjects.forEach(tItem => {
          if (tItem.no === item.subjectNo) {
            tItem.flag = false
          }
        })
      })
    },

    // refreshClassRoom () {
    //   this.selectClassRoomFn()
    // },
    // 任课老师输入联想
    // async querySearch (queryString, cb) {
    //   let query = {
    //     accountStatus: 1,
    //     positionType: '1',
    //     name: queryString,
    //     pageNum: 1,
    //     pageSize: 10
    //   }
    //   let restaurants = []
    //   let res = await queryPage(query)
    //   await res.data.records.forEach(item => {
    //     let obj = {}
    //     obj.name = item.name
    //     obj.value = item.no
    //     restaurants.push(obj)
    //   })
    //   cb(restaurants)
    // },

    // 点击修改教师 保存当前行index
    focusFn (index) {
      this.currentTeacherRow = index
    },

    // 接受修改后老师的值
    selectItemFn (val) {
      this.teacherTableData[this.currentTeacherRow].teacherNo = val.value
    },

    // 新增教师
    addTeacherFn () {
      this.addTeachForm.flag = true
      this.addTeachForm.title = '新增教职工信息'
      this.infoData = this.$dictionary
      this.addTeachFormData = {
        isCreateAccount: 1,
        gender: 0,
        cardType: '1',
        nationality: '156',
        positionType: '0'
      }
    },

    // 部门数据
    queryDeptListBySchoolNo () {
      queryDeptListBySchoolNo({}).then(res => {
        this.departments = res.data
      })
    },

    // 新增教室
    addClassRoomFn () {
      this.$refs.classroomInfoModal.isAdd = true
      this.$refs.classroomInfoModal.add()
    },

    modalOk () {
      this.selectClassRoomFn()
    },

    // 提交表单
    async hanldeSave (editFormRef) {
      let subjects = []
      let flag = false
      // 任课教师表的数据检查
      this.teacherTableData.forEach(item => {
        let obj = {}
        obj.subjectNo = item.subjectNo
        obj.teacherNo = item.teacherNo
        subjects.push(obj)
        if (!item.subjectNo || !item.teacherNo) {
          flag = true
        }
      })
      if (flag) {
        Message({
          type: 'warning',
          message: '课程或任课教师未选择！'
        })
        subjects = []
        return
      }
      this.reqFormData(subjects, editFormRef)
    },

    // 提交表单 请求
    async reqFormData (subjects, editFormRef) {
      this.$refs[editFormRef].validate(async valid => {
        if (valid) {
          let res
          let SepClassesUpdateReq = {
            classRoomNo: this.editForm.classRoomNo || this.SepClassesUpdateReq.classRoomNo, // string 教室编号
            classSection: this.editForm.classSection || '', // string 班级学段
            classSize: this.editForm.classSize || '', // string 班级人数
            gradeNo: this.editForm.gradeNo || this.SepClassesUpdateReq.gradeNo, // string 年级编号
            headerNo: this.editForm.headerNo || this.SepClassesUpdateReq.headerNo, // string 老师编号
            name: this.editForm.name || '', // string 班级名称,
            status: this.editForm.status || this.SepClassesUpdateReq.status,
            no: this.editForm.classNo, // 班级编号
            subjects
            // ...this.editForm
          }
          try {
            res = await editorClass(SepClassesUpdateReq)
            if (res.code === 0) {
              this.dialogVisible = false
              this.$emit('ok')
            } else {
              Message({
                type: 'error',
                message: res.msg
              })
            }
          } catch (e) {}
        }
      })
    },

    // 取消新增
    handleCancel () {
      this.dialogVisible = false
      this.editForm = Object.assign({}, this.editForm)
    },
    addCourseFn () {
      this.teacherTableData.push({ subjectNo: '', teacherName: '' })
      this.filterItem()
    },
    // 修改任课教师
    editTeacherFn (rowD, index) {
      // 保存当前行
      this.currentRow = index
      let type = 'editor'
      this.$refs.addTeacher.add({ rowD, type })
    },
    // 选择老师
    chooseTeacher () {
      let rowD = {}
      let type = 'addHeaderName'
      this.$refs.addTeacher.add({ rowD, type })
    },
    // 接收选择返回的老师
    addTeacherReq (data) {
      if (data.type === 'headName') {
        // 选择班主任
        this.editForm.headerNo = data.data.no
        this.headerName = data.data.name
        // this.headerN = data.data.name
      } else {
        this.teacherTableData[this.currentRow].teacherName = data.data.name
        this.teacherTableData[this.currentRow].teacherNo = data.data.no
        this.i++
      }
    }
  },
  mounted () {}
}
</script>
<style scoped lang="scss">
.dialog-footer {
  text-align: right;
}

/deep/ .el-rate__item {
  padding-top: 5px;
  .el-rate__icon {
    font-size: 22px;
  }
}
/deep/ .img-over {
  margin-right: 5px;
  width: 60px;
  height: 45px;
  cursor: pointer;
}
/deep/ .viewer-container {
  z-index: 3000 !important;
}
.line{
  display: inline-block;
  width: 700px;
}
.selectWidth {
    width: 230px;
}
.teacherBtn {
  display: flex;
  width: 557px;
  position: relative;
  .btns {
    position: absolute;
    left: 29.4%;
    bottom: 1px;
    height: 32px;
  }
}
.selectHead1 {
  width: 218px;
}
.choose {
  height:32px;
}
.classRoom {
  display: flex;
  width: 490px;
}
// .choose {
//   margin-left: -40px;
//   z-index: 11;
// }
.itemWrapper {
    margin: 10px 0;
  .itemTitle {
    margin-left: 20px;
    height:40px;
    line-height:40px;
    font-size: 18px;
    font-weight: 600;
  }
  .itemBtn {
      margin-right: 20px;
      float: right;
  }
}
.inputWidth {
  width: 370px;
}
.selectHead {
  width: 230px;
}
.subjectSelect {
  display: inline-block;
  width: 180px;
}
.btnCss {
  height: 44px;
  // margin-left: -54px;
  // z-index: 999;
}
</style>
